<?php

namespace app\api\service\shop;

use app\admin\model\factor\CarbonFactor;
use app\admin\model\template\Order;
use app\admin\model\template\OrderCommissionRecord;
use app\admin\model\template\Template;
use think\Db;

/**
 * 我的信息
 */
class MyInfoService
{

    /**
     * 获取总的收益
     * @param int $userId 用户ID
     */
    public function getProfitTotal(int $userId)
    {
        $sql = $this->getProfitSql($userId);
        return Db::name('order')
            ->alias('o')
            ->join("($sql) c", 'o.id = c.order_id')
            ->where('o.pay_state', 1)
            ->sum('c.fee');
    }

    /**
     * 获取所有收益的联合语句
     * @param int $userId 用户ID
     */
    private function getProfitSql(int $userId)
    {
        return Db::name('order_commission_record')
            ->where('author_id', $userId)
            ->field(['order_id', 'fee', '1 type'])
            ->union(function ($query) use ($userId) {
                $query->table('zt_order_factor')
                    ->where('from_user', $userId)
                    ->fieldRaw('order_id, sum(price) fee, 2 type')
                    ->group('order_id');
            })
            ->union(function ($query) use ($userId) {
                $query->table('zt_order_template')
                    ->where('from_user', $userId)
                    ->fieldRaw('order_id, sum(commission) fee, 3 type')
                    ->group('order_id');
            })
            ->fetchSql()
            ->select();
    }

    /**
     * 获取区间收益
     * @param int $userId 用户ID
     * @param int $startTime 起始时间
     * @param int $endTime 结束时间
     */
    public function getProfitBetween(int $userId, int $startTime, int $endTime)
    {
        $sql = $this->getProfitSql($userId);

        return Db::name('order')
            ->alias('o')
            ->join("($sql) c", 'o.id = c.order_id')
            ->where('o.pay_state', 1)
            ->whereBetween('createtime', [$startTime, $endTime])
            ->sum('c.fee');
    }

    /**
     * 获取收益列表
     * @param int $userId 用户ID
     * @param int $page 页码
     * @param int $limit 每页展示数据
     * @param int|null $typeId 收益类型,1 - 模板、2 - 因子、3 - 分成
     */
    public function getProfitRecord(int $userId, int $page, int $limit, int $typeId = null)
    {
        switch ($typeId) {
            case 1: // 查询模板收益
                $sql = Db::name('order')
                    ->alias('o')
                    ->join('zt_order_commission_record r', 'o.id = r.order_id')
                    ->where(['o.pay_state' => 1, 'r.type' => 1, 'r.author_id' => $userId])
                    ->field(['o.id order_id', 'o.createtime', 'r.fee', 'o.order_sn', '1 type']);
                break;
            case 2: // 查询因子收益
                $sql = Db::name('order')
                    ->alias('o')
                    ->join('zt_order_factor f', 'o.id = f.order_id')
                    ->where(['o.pay_state' => 1, 'f.from_user' => $userId])
                    ->field(['o.id order_id', 'o.createtime', 'f.price fee', 'o.order_sn', '2 type']);
                break;
            case 3: // 查询模板分成收益
                $sql = Db::name('order')
                    ->alias('o')
                    ->join('zt_order_template t', 'o.id = t.order_id')
                    ->where(['o.pay_state' => 1, 't.from_user' => $userId])
                    ->field(['o.id order_id', 'o.createtime', 't.commission fee', 'o.order_sn', '3 type']);
                break;
            default: // 全部查询
                $sql = $this->getProfitSql($userId);
                $sql = Db::name('order')
                    ->alias('o')
                    ->join("($sql) c", 'o.id = c.order_id')
                    ->where('o.pay_state', 1)
                    ->field(['c.order_id', 'o.createtime', 'c.fee', 'o.order_sn', 'c.type']);
                break;
        }

        $data = $sql->order('createtime', 'desc')->paginate($limit)
            ->each(function ($item) {
                $data = [1 => '碳足迹核算模板', 2 => '碳排放因子&数据库', 3 => '碳足迹核算模板分成'];
                $item['type_name'] = $data[$item['type']];
                return $item;
            });
        return ['total' => $data->total(), 'row' => $data->items()];
    }

    /**
     * 获取我上架的
     * @param int $userId 用户ID
     */
    public function getShelves(int $userId)
    {
        return Template::alias('t')
            ->join('zt_product p', 't.product_id = p.id')
            ->join('zt_carbon_factor f', 'f.user_id = p.user_id')
            ->where(['p.user_id' => $userId])
            ->whereOr(['f.user_id' => $userId])
            ->count();
    }


    /**
     * 获取我的购买
     * @param int $userId 用户ID
     * @param int $companyId 公司ID
     * @param bool $type 是否是公司
     */
    public function getBuy(int $userId, int $companyId, bool $type = true)
    {
        $where = ['user_id' => $userId];
        $where['company_id'] = $type ? $companyId : null;
        return Order::where($where)->count();
    }

    /**
     * 获取我的出售
     * @param int $userId 用户ID
     * @param int $companyId 公司ID
     * @param bool $type 是否是公司
     */
    public function getSell(int $userId, int $companyId, bool $type = true)
    {
        $where = ['author_id' => $userId];
        $where['company_id'] = $type ? $companyId : 0;
        $sum = OrderCommissionRecord::where($where)->count('id');
        $sum += Db::name('order_factor')->where('from_user', $userId)->count('order_id');
        $sum += Db::name('order_template')->where('from_user', $userId)->count('order_id');
        return $sum;
    }

    /**
     * 获取我上架的列表
     * @param int $userId 用户ID
     * @param int $type 1 - 获取模板、2 - 获取因子、3 - 获取全部
     * @param int $page 页码
     * @param int $limit 每页展示数据
     */
    public function getMyShelvesList(int $userId, int $type, int $page, int $limit)
    {
        $where = ['user_id' => $userId];
        switch ($type) {
            case 1:
                return Template::where($where)
                    ->whereIn('id', Db::name('template_review')
                        ->where($where)
                        ->distinct(true)
                        ->column('template_id')
                    )
                    ->field(['id', 'product_name name', 'sn', 'check_status status', 'sales', 'createtime', 'product_id'])
                    ->order('createtime desc')
                    ->page($page)
                    ->limit($limit)
                    ->select()
                    ->each(function ($item) {
                        $item['product_sn'] = $item->product?->sn;
                        $item['type'] = '核算模板';
                        $item['type_id'] = 1;
                        $item->hidden(['product']);
                    });
            case 2:
                return CarbonFactor::where($where)
                    ->whereIn('id', CarbonFactor::alias('c')
                        ->where($where)
                        ->join('zt_carbon_factor_review r', 'c.id = r.factor_id')
                        ->distinct(true)
                        ->column('c.id'))
                    ->field(['id', 'name', 'sn', 'product_review status', 'sales', 'createtime', 'null product_sn', '0 product_id'])
                    ->order('createtime desc')
                    ->page($page)
                    ->limit($limit)
                    ->select()
                    ->each(function ($item) {
                        $item['type'] = '碳数据';
                        $item['type_id'] = 2;
                    });
            default:
                return CarbonFactor::where($where)
                    ->whereIn('id', CarbonFactor::alias('c')
                        ->where($where)
                        ->join('zt_carbon_factor_review r', 'c.id = r.factor_id')
                        ->distinct(true)
                        ->column('c.id'))
                    ->field(['id', 'name', 'sn', 'product_review status', 'sales', 'createtime', '2 type_id', 'null product_sn', '0 product_id'])
                    ->union(function ($query) use ($where) {
                        $query->where($where)
                            ->whereIn('id', Db::name('template_review')
                                ->where($where)
                                ->distinct(true)
                                ->column('template_id')
                            )
                            ->field(['id', 'product_name name', 'sn', 'check_status status', 'sales', 'createtime', '1 type_id', 'null product_sn', 'product_id'])
                            ->table('zt_template');
                    })->order('createtime desc')
                    ->page($page)
                    ->limit($limit)
                    ->select()
                    ->each(function ($item) {
                        if ($item->type_id == 1) $item->product_sn = Db::name('product')->where('id', $item->product_id)->value('sn');
                        $data = [1 => '核算模板', 2 => '碳数据'];
                        $item['type'] = $data[$item['type_id']];
                        return $item;
                    });
        }
    }

    /**
     * 我的上架数量
     * @param int $userId 用户ID
     */
    public function getMyShelves(int $userId)
    {
        $where = ['user_id' => $userId];
        $template = Template::where($where)->whereIn('id', Db::name('template_review')
            ->where($where)
            ->distinct(true)
            ->column('template_id')
        )->count();
        $carbonFactor = CarbonFactor::where($where)
            ->whereIn('id', CarbonFactor::alias('c')
                ->where($where)
                ->join('zt_carbon_factor_review r', 'c.id = r.factor_id')
                ->distinct(true)
                ->column('c.id'))
            ->count('id');
        return ['template' => $template, 'carbonFactor' => $carbonFactor, 'total' => $template + $carbonFactor];
    }

}